﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using WinHBM.Core.Net.Http;
using System.Windows.Forms;
using WinHBM.Core.Bluetooth;
using InTheHand.Net.Sockets;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;

namespace WinHBM.Core.Net.Sockets.Cmd
{
    public class BluetoothBindCmd : SocketCmd
    {
        
        private HttpClient httpClient = HttpClient.Instance;
        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(BluetoothBindCmd));
        public override void executeCmd(JObject request, FlashSocketServer socket)
        {
            if (BluetoothClientHolder.bluetoothClient == null)
            {
                socket.Send(wrapCmd(CMD_BLUETOOTH_BIND, "未连接"));
                return;
            }
            string address = request["address"].ToString();
            int teacherId = Int32.Parse(request["teacherId"].ToString());
            MagicBar bar = new MagicBar(BluetoothClientHolder.bluetoothClient);
            if (bar.CMD_BindTeacherId(teacherId))
            {
                //设置音量
                Thread.Sleep(3000);
                bar.CMD_SettingVoice(10);
                JObject data = new JObject();
                data["barcode"] = address;
                httpClient
                .CreateRequest("/api/user-role/bind-bar", RequestMethod.POST, data)
                .send((response, json) => {
                    //更新mac地址到user.bin
                    UserInfo userinfo = UserInfo.INSTANCE;
                    userinfo.Address = address;
                    userinfo.commit();
                    socket.Send(wrapCmd(CMD_BLUETOOTH_BIND, json));
                    


                }, (response, exception) => {
                    socket.Send(wrapCmd(CMD_BLUETOOTH_BIND, "绑定失败"));
                });
            }
            else
            {
                socket.Send(wrapCmd(CMD_BLUETOOTH_BIND, "绑定失败"));
            }
            
        }

        
    }
}
